package com.cheng.service;

import com.cheng.spring.BeanPostProcessor;
import com.cheng.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author chengjunjie
 * @date 2025-10-13
 */

@Component
public class ChengBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        // 可以批量处理bean ｜ 单出处理针对beanName进行处理或者针对bean对象类型进行处理
        if (beanName.contains("userService")) {
            System.out.println("初始化前");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if (beanName.contains("userService")) {
            // JDK 动态代理 接口才能被代理
            return Proxy.newProxyInstance(ChengBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("切面逻辑");
                    // 调用被代理的方法
                    return method.invoke(bean, args);
                }
            });
        }
        return bean;
    }
}
